#include  "../source/server.hpp"

// int main()
// {
//     Socket lst_sock;
//     lst_sock.CreateServer(8500);
//     while(1)
//     {
//         int newfd = lst_sock.Accept();
//         if(newfd < 0)
//         {
//             continue;
//         }
//         Socket cli_sock(newfd);
//         char buf[1024] = {0};
//         int ret = cli_sock.Recv(buf, 1023);
//         if(ret < 0)
//         {
//             cli_sock.Close();
//             continue;
//         }
//         cli_sock.Send(buf,1023);
//     }
//     return 0;
// }

// void HandlerClose(Channel* channel)
// {
//     // std::cout << "close: " <<channel->Fd() <<std::endl;
//     DBG_LOG("close fd:%d", channel->Fd());
//     channel->Remove();
//     delete channel;
// }
// void HandleRead(Channel* channel)
// { 
//     DBG_LOG("HandleRead");
//     int fd = channel->Fd();
//     char buf[1024] = {0};
//     int ret = recv(fd, buf, 1023, 0);
//     if(ret <= 0)
//     {
//         return HandlerClose(channel); //关闭释放
//     }

//     DBG_LOG("%s", buf);
//     channel->EnAbleWrite(); //启动可写事件
// }
// void HandleWrite(Channel* channel)
// {
//     int fd = channel->Fd();
//     const char* data = "天气还不错！！";
//     int ret = send(fd, data, strlen(data), 0);
//     if(ret < 0)
//     {
//         return HandlerClose(channel);//关闭释放
//     }
//     channel->DisAbleWrite(); //关闭可写监控
// }
// void HandleError(Channel* channel)
// {
//     return HandlerClose(channel);//关闭释放
// }
// void HandleEvent( EventLoop* loop ,Channel* channel, uint64_t timerid)
// {
//     loop->TimerRefresh(timerid);
//     // std::cout<< "有了一个事件！！" << std::endl;
// }

// void Acceptor(Poller* poller, Channel* lst_channel)
// {
//      int fd = lst_channel->Fd();
//      int newfd = accept(fd, NULL, NULL);
//      if(newfd < 0) {return; }
//      Channel* channel = new Channel(poller, newfd);
//      channel->SetReadCallback(std::bind(HandleRead, channel)); //为通信套接字设置可读事件的回到函数
//      channel->SetWriteCallback(std::bind(HandleWrite, channel)); //可写事件的回调函数
//      channel->SetCloseCallback(std::bind(HandlerClose, channel)); //关闭事件的回调函数
//      channel->SetErrorCallback(std::bind(HandleError, channel)); //错误事件的回调函数
//      channel->SetEventCallback(std::bind(HandleEvent, channel)); //任意事件的回调函数
//      channel->EnAbleRead();
// }
//Poller测试Channel联合
// int main()
// {
//     Poller poller;
//     Socket lst_sock;
//     lst_sock.CreateServer(8500);
//     //为监听套接字，创建一个Channel进行事件的管理，以及事件的处理
//     Channel channel(&poller, lst_sock.Fd());
//     channel.SetReadCallback(std::bind(Acceptor, &poller, &channel)); //回调中，获取新连接，为新连接创建Channel并且添加监控
//     channel.EnAbleRead();
//     while(1)
//     {
//         std::vector<Channel*> actives;
//         poller.Poll(&actives);
//         for(auto &a : actives)
//         {
//             a->HandleEvent();
//         }
//         lst_sock.Close();
//     }
//     return 0;
// }


//测试loop 和timer
// void Acceptor(EventLoop* loop, Channel* lst_channel)
// {
//      int fd = lst_channel->Fd();
//      int newfd = accept(fd, NULL, NULL);//会阻塞
//      if(newfd < 0) {return; }

//      uint64_t timerid = rand()%10000;
//      Channel* channel = new Channel(loop, newfd);
//      channel->SetReadCallback(std::bind(HandleRead, channel)); //为通信套接字设置可读事件的回到函数
//      channel->SetWriteCallback(std::bind(HandleWrite, channel)); //可写事件的回调函数
//      channel->SetCloseCallback(std::bind(HandlerClose, channel)); //关闭事件的回调函数
//      channel->SetErrorCallback(std::bind(HandleError, channel)); //错误事件的回调函数
//      channel->SetEventCallback(std::bind(HandleEvent, loop, channel, timerid)); //任意事件的回调函数

//      //非活跃连接的超时释放操作，10s后关闭连接 
//      //注意：定时销毁任务，必须在启动读事件之前，因为有可能启动了事件监控后，立即就有了事件，但是这时候还没有任务
//      loop->TimerAdd(timerid, 10, std::bind(HandlerClose, channel));
//      channel->EnAbleRead();

// }



//Connection测试

//管理所有连接
// std::unordered_map<uint64_t, PtrConnection> _conns;
// uint64_t conn_id = 0;
// void ConnectionDestroy(const PtrConnection &conn)
// {
//     _conns.erase(conn->Id());
// }

// void OnConnected(const PtrConnection &conn)
// {
//     DBG_LOG("NEW CONNECTION:%p", conn.get());
// }
// void OnMessage(const PtrConnection &conn, Buffer* buf)
// {
//     DBG_LOG("%s", buf->ReadPosition());
//     buf->MoveReadOffset(buf->ReadAbleSize());
//     std::string str = "Hello World";
//     conn->Send(str.c_str(), str.size());
// }
// void Acceptor(EventLoop* loop, Channel* lst_channel)
// {
//     int fd = lst_channel->Fd();
//     int newfd = accept(fd, NULL, NULL);
//     if(newfd < 0) { return; }

//     conn_id++;
//     PtrConnection conn(new Connection(loop, conn_id, newfd));
//     conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
//     conn->SetClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
//     conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
//     conn->EnableInactiveRelease(10); //启动非活跃超时销毁
//     conn->Established();//就绪初始化
//     _conns.insert(std::make_pair(conn_id, conn));
// }

// int main()
// {
//     srand(time(NULL));
//     EventLoop loop;
//     Socket lst_sock;
//     lst_sock.CreateServer(8500);
//     //为监听套接字，创建一个Channel进行事件管理，以及事件的处理
//     Channel channel(&loop, lst_sock.Fd());
//     //回调中，获取新连接，为新连接创建一个Channel并且添加监控
//     channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));
//     channel.EnAbleRead();

//     loop.Start();
//     lst_sock.Close();
//     return 0;
// }


// Acceptor测试
// EventLoop loop;
// std::unordered_map<uint64_t, PtrConnection> _conns;
// uint64_t conn_id = 0;
// void ConnectionDestroy(const PtrConnection &conn)
// {
//     _conns.erase(conn->Id());
// }

// void OnConnected(const PtrConnection &conn)
// {
//     DBG_LOG("NEW CONNECTION:%p", conn.get());
// }
// void OnMessage(const PtrConnection &conn, Buffer* buf)
// {
//     DBG_LOG("%s", buf->ReadPosition());
//     buf->MoveReadOffset(buf->ReadAbleSize());
//     std::string str = "Hello World";
//     conn->Send(str.c_str(), str.size());
// }
// void NewConnection(int newfd)
// {
//     conn_id++;
//     PtrConnection conn(new Connection(&loop, conn_id, newfd));
//     conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
//     conn->SetClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
//     conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
//     conn->EnableInactiveRelease(10); //启动非活跃超时销毁
//     conn->Established();//就绪初始化
//     _conns.insert(std::make_pair(conn_id, conn));
// }

// int main()
// {
//     srand(time(NULL));

//     Acceptor acceptor(&loop, 8500);
//     //回调中，获取新连接，为新连接创建一个Channel并且添加监控
//     acceptor.SetReadCallback(std::bind(NewConnection, std::placeholders::_1));
//     acceptor.Listen();
//     loop.Start();

//     return 0;
// }



// LoopThread测试
// std::unordered_map<uint64_t, PtrConnection> _conns;
// EventLoop base_loop;
// uint64_t conn_id = 0;
// std::vector<LoopThread> threads(2);
// int next_loop = 0;

// void ConnectionDestroy(const PtrConnection &conn)
// {
//     _conns.erase(conn->Id());
// }

// void OnConnected(const PtrConnection &conn)
// {
//     DBG_LOG("NEW CONNECTION:%p", conn.get());
// }
// void OnMessage(const PtrConnection &conn, Buffer* buf)
// {
//     DBG_LOG("%s", buf->ReadPosition());
//     buf->MoveReadOffset(buf->ReadAbleSize());
//     std::string str = "Hello World";
//     conn->Send(str.c_str(), str.size());
// }
// void NewConnection(int newfd)
// {
//     conn_id++;
//     next_loop = (next_loop + 1) % 2;
//     PtrConnection conn(new Connection(threads[next_loop].GetLoop(), conn_id, newfd));
//     conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
//     conn->SetClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
//     conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
//     conn->EnableInactiveRelease(10); //启动非活跃超时销毁
//     conn->Established();//就绪初始化
//     _conns.insert(std::make_pair(conn_id, conn));
//     DBG_LOG("--------------New");
// }

// int main()
// {
//     srand(time(NULL));

//     Acceptor acceptor(&base_loop, 8500);

//     //回调中，获取新连接，为新连接创建一个Channel并且添加监控
//     acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));

//     acceptor.Listen();
//     DBG_LOG("--------------contiue");

//     base_loop.Start();

//     return 0;
// }



// LoopThreadPool测试
std::unordered_map<uint64_t, PtrConnection> _conns;
EventLoop base_loop;
uint64_t conn_id = 0;
std::vector<LoopThread> threads(2);
int next_loop = 0;
LoopThreadPool *loop_pool;

void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}



void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());
}
void NewConnection(int newfd)
{
    conn_id++;
    next_loop = (next_loop + 1) % 2;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, newfd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10); //启动非活跃超时销毁
    conn->Established();//就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("--------------New");
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();

    Acceptor acceptor(&base_loop, 8500);

    //回调中，获取新连接，为新连接创建一个Channel并且添加监控
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));

    acceptor.Listen();
    DBG_LOG("--------------contiue");

    base_loop.Start();

    return 0;
}